import java.io.*;
import java.net.*;
import java.util.Calendar;

public class PolicyServerConnection extends Thread {
    protected Socket socket;
    protected BufferedReader socketIn;
    protected PrintWriter socketOut;
    
    /**
     * Creates a new instance of PolicyServerConnection.
     *
     * @param socket client's socket connection
     */
    public PolicyServerConnection(Socket socket) {
        this.socket = socket;
    }
    
    /**
     * Create a reader and writer for the socket and call readPolicyRequest.
     */
    public void run() {
        try {
            this.socketIn = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            this.socketOut = new PrintWriter(this.socket.getOutputStream(), true);
            
            String request = read();
            
            if (request.equals(PolicyServer.POLICY_REQUEST)) {
                this.socketOut.write(PolicyServer.POLICY_REPLY + "\u0000");
                this.socketOut.flush();
                String time = "[" + Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + "] ";
                System.out.println( time + "Sent Policy File to " + socket.getRemoteSocketAddress() );
            }

            this.socketIn.close(); 
            this.socketOut.close();
            System.out.println( "Closing policy connection from " + socket.getRemoteSocketAddress() );
            this.socket.close();
        }
        catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
    
    
    /**
     * Safely read a string from the reader until a zero character is received or the 200 character is reached.
     *
     * @return the string read from the reader.
     */
    protected String read() {
        StringBuffer buffer = new StringBuffer();
        int codePoint;
        boolean zeroByteRead = false;
        
        try {
            do {
                codePoint = this.socketIn.read();

                if (codePoint == 0) {
                    zeroByteRead = true;
                }
                else if (Character.isValidCodePoint(codePoint)) {
                    buffer.appendCodePoint(codePoint);
                }
            }
            while (!zeroByteRead && buffer.length() < 200);
        }
        catch (Exception e) {
            System.out.println("Exception (read): " + e.getMessage());
        }
        
        return buffer.toString();
    }
}
